package com.example.myviewmodelframe.base.activity

import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.example.myviewmodelframe.R
import com.example.myviewmodelframe.base.event.BaseActionEvent
import com.example.myviewmodelframe.base.model.BaseViewModel
import com.example.myviewmodelframe.base.model.BaseViewModelFactory


/**
 * @author tgw
 * @date 2021/6/10
 * @describe
 */
abstract class  BaseActivity<VB : ViewBinding, VM : BaseViewModel> : AppCompatActivity() {

    private var baseView: View? = null
    private lateinit var baseViewModel: BaseViewModel
    protected lateinit var mBind: VB
    private var loadingDialog: ProgressBar? = null

    abstract fun getViewBinding(): VB
    abstract fun getViewModel(): VM

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 全屏、隐藏状态栏
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )

        mBind = getViewBinding()
        setContentView(mBind.root)

        val rootView = findViewById<FrameLayout>(R.id.content)

        baseView = LayoutInflater.from(this).inflate(R.layout.activity_base_main, rootView, false)
        addContentView(
            baseView,
            ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        )
        baseView?.visibility = View.GONE


//        baseViewModel = BaseViewModelFactory().create(BaseViewModel::class.java)
//      var  aa : BaseViewModel by viewModels()


        baseViewModel = getViewModel()

        /**网络请求加载样式*/
        baseViewModel.getActionLiveData()?.observe(this, {
            when (it.action) {
                BaseActionEvent.SHOW_LOADING_DIALOG -> startLoading(it.message)
                BaseActionEvent.DISMISS_LOADING_DIALOG -> hindLoading(it.message)
                BaseActionEvent.SHOW_TOAST -> it.message
            }
        })
        /**生命周期*/
//        baseViewModel.lifecycleOwner = this

    }

    private fun startLoading(message: String?) {
        Log.d("tgw", "startLoading: " + message)
        baseView?.visibility = View.VISIBLE
//        baseView?.setOnClickListener(null)
        baseView?.isClickable = true
//        baseView?.setOnClickListener{v->{
//
//        }}
//        baseView?.setOnTouchListener { v: View, _ ->
//            var aa = 1
//            return@setOnTouchListener false
//        }

    }

    private fun hindLoading(message: String?) {
        Log.d("tgw", "hindLoading: " + message)
        baseView?.visibility = View.GONE
    }

    override fun onDestroy() {
        hindLoading(null)
        super.onDestroy()
    }

}